package com.app.studyroom.adapter;

import android.content.Context;
import android.content.SharedPreferences;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.DatePicker;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.widget.AppCompatSpinner;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.app.studyroom.ClassActivity;
import com.app.studyroom.R;
import com.app.studyroom.api.ApiClient;
import com.app.studyroom.api.ApiResponse;
import com.app.studyroom.api.ApiService;
import com.app.studyroom.api.model.ssrGet.OpenStatusResponse;
import com.app.studyroom.api.model.ssrBooking.BookingSaveRequest;
import com.app.studyroom.api.model.ssrSeat.PageSeatListRequest;
import com.app.studyroom.api.model.ssrSeat.PageSeatListResponse;
import com.app.studyroom.api.model.ssrSeat.SeatItem;
import com.app.studyroom.api.model.ssrSeat.SsrSeatBooking;
import com.app.studyroom.api.model.ssrUser.QyAdminListRequest;
import com.app.studyroom.api.model.ssrUser.UserItem;
import com.app.studyroom.dialog.CustomSizeDialog;
import com.app.studyroom.mapper.SeatMapper;
import com.app.studyroom.model.LayoutElement;
import com.google.gson.Gson;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class ClassLayoutElementAdapter extends RecyclerView.Adapter<ClassLayoutElementAdapter.ElementHolder> {

    private final List<LayoutElement> elements;
    private final Context context;

    private final boolean enableReservation;

    public ClassLayoutElementAdapter(Context context, List<LayoutElement> elements, boolean enableReservation) {
        this.context = context;
        this.elements = elements;
        this.enableReservation = enableReservation;
    }


    @Override
    public int getItemViewType(int position) {
        LayoutElement element = elements.get(position);
        if (element == null) return -1;
        switch (element.type) {
            case "seat": return 0;
            case "window": return 1;
            case "door": return 2;
            case "spacer": return 3;
            default: return -1;
        }
    }

    @Override
    public ElementHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        LayoutInflater inflater = LayoutInflater.from(context);
        View view;
        switch (viewType) {
            case 0: view = inflater.inflate(R.layout.seat_item, parent, false); break;
            case 1: view = inflater.inflate(R.layout.item_window, parent, false); break;
            case 2: view = inflater.inflate(R.layout.item_door, parent, false); break;
            default:
                view = new View(context);
                view.setLayoutParams(new ViewGroup.LayoutParams(1, 1));
                break;
        }
        return new ElementHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull ElementHolder holder, int position) {
        LayoutElement element = elements.get(position);
        if (element == null) return;

        switch (element.type) {
            case "seat":
                ImageView seatImage = holder.itemView.findViewById(R.id.seat_image);
                TextView seatText = holder.itemView.findViewById(R.id.seat_id_text);
                seatText.setText(String.valueOf(element.id));
                int iconRes;
                switch (element.seatStatus) {
                    case "1": iconRes = R.drawable.picture1; break; // 占用
                    case "2": iconRes = R.drawable.picture2; break; // 维护中
                    case "3": iconRes = R.drawable.picture3; break; // 已预约
                    case "4": iconRes = R.drawable.picture3; break; // 申请中
                    case "5": iconRes = R.drawable.picture5; break; // 已绑定
                    default:  iconRes = R.drawable.picture0; break; // 空闲
                }
                seatImage.setImageResource(iconRes);

                holder.itemView.setOnClickListener(v -> {
                    if (!enableReservation) return; // 🔒 禁止预约时直接 return

                    switch (element.seatStatus) {
//                        case "1": Toast.makeText(context, "座位已被占用", Toast.LENGTH_SHORT).show(); return;
                        case "2": Toast.makeText(context, "座位维护中", Toast.LENGTH_SHORT).show(); return;
                    }
                    //绑定的逻辑
                    SharedPreferences sp = context.getSharedPreferences("Session", Context.MODE_PRIVATE);
                    boolean isBind = sp.getBoolean("isBind", false);
                    String bindSeatPlace = sp.getString("bindSeatPlace", null);
                    String bindSeatNum = sp.getString("bindSeatNum", null);

                    // 当前点击的座位
                    String frontendRoomName = SeatMapper.getFrontendRoom(element.roomId);
                    String backendRoomId = SeatMapper.getBackendRoom(frontendRoomName);
                    String backendSeatNum = SeatMapper.getBackendSeatNum(element.id);


                    if ("5".equals(element.seatStatus)) {
                        if (!isBind || !backendRoomId.equals(bindSeatPlace) || !backendSeatNum.equals(bindSeatNum)) {
                            Toast.makeText(context, "该座位已绑定，您无权预约", Toast.LENGTH_LONG).show();
                            return;
                        }
                    }

                    // 如果已绑定但当前座位不是绑定座位，直接拒绝预约
                    if (isBind && (!backendRoomId.equals(bindSeatPlace) || !backendSeatNum.equals(bindSeatNum))) {
                        Toast.makeText(context, "您已绑定座位【" + bindSeatPlace + "-" + bindSeatNum + "】，不可预约其他座位", Toast.LENGTH_LONG).show();
                        return;
                    }

                    /// ////////////////////

                    if (backendRoomId == null || backendSeatNum == null) {
                        Toast.makeText(context, "无法识别座位信息", Toast.LENGTH_SHORT).show();
                        return;
                    }

                    showReservationDialog(context, backendRoomId, backendSeatNum, element.roomId, element.id);

                });
                break;

            case "spacer":
                int widthDp = element.width > 0 ? element.width : 40;
                int heightDp = element.height > 0 ? element.height : 60;
                int widthPx = (int) (context.getResources().getDisplayMetrics().density * widthDp + 0.5f);
                int heightPx = (int) (context.getResources().getDisplayMetrics().density * heightDp + 0.5f);
                holder.itemView.setLayoutParams(new ViewGroup.LayoutParams(widthPx, heightPx));
                break;
            case "window":
                widthDp = element.width > 0 ? element.width : 40;
                heightDp = element.height > 0 ? element.height : 60;
                widthPx = (int) (context.getResources().getDisplayMetrics().density * widthDp + 0.5f);
                heightPx = (int) (context.getResources().getDisplayMetrics().density * heightDp + 0.5f);

                // 设置 item 宽高
                holder.itemView.setLayoutParams(new ViewGroup.LayoutParams(widthPx, heightPx));

                // 设置内部 label 的宽度
                TextView window_label = holder.itemView.findViewById(R.id.window_label);
                if (window_label != null) {
                    ViewGroup.LayoutParams labelParams = window_label.getLayoutParams();
                    labelParams.width = widthPx;
                    labelParams.height = heightPx;
                    window_label.setLayoutParams(labelParams);
//                    label.setText("窗户"); // 可选
                }
                break;

            case "door":
                widthDp = element.width > 0 ? element.width : 40;
                heightDp = element.height > 0 ? element.height : 60;
                widthPx = (int) (context.getResources().getDisplayMetrics().density * widthDp + 0.5f);
                heightPx = (int) (context.getResources().getDisplayMetrics().density * heightDp + 0.5f);
                // 设置 item 宽高
                holder.itemView.setLayoutParams(new ViewGroup.LayoutParams(widthPx, heightPx));

                //设置门方向
                ImageView doorImage = holder.itemView.findViewById(R.id.bg_ic_door);
                if (doorImage != null && element.direction != null) {
                    switch (element.direction) {
                        case "left":
                            doorImage.setRotation(270f);
                            break;
                        case "right":
                            doorImage.setRotation(90f);
                            break;
                        case "up":
                            doorImage.setRotation(0f);
                            break;
                        case "down":
                            doorImage.setRotation(180f);
                            break;
                        case "mirror-left-horizontal":  // 水平镜像
                            doorImage.setScaleX(-1f);
                            doorImage.setRotation(270f);
                            break;
                        case "mirror-left-vertical":    // 垂直镜像
                            doorImage.setScaleY(-1f);
                            doorImage.setRotation(270f);
                            break;
                        case "mirror-right-horizontal":  // 水平镜像
                            doorImage.setScaleX(-1f);
                            doorImage.setRotation(90f);
                            break;
                        case "mirror-right-vertical":    // 垂直镜像
                            doorImage.setScaleY(-1f);
                            doorImage.setRotation(90f);
                            break;
                        case "mirror-up-horizontal":  // 水平镜像
                            doorImage.setScaleX(-1f);
                            doorImage.setRotation(0f);
                            break;
                        case "mirror-up-vertical":    // 垂直镜像
                            doorImage.setScaleY(-1f);
                            doorImage.setRotation(0f);
                            break;
                        case "mirror-down-horizontal":  // 水平镜像
                            doorImage.setScaleX(-1f);
                            doorImage.setRotation(180f);
                            break;
                        case "mirror-down-vertical":    // 垂直镜像
                            doorImage.setScaleY(-1f);
                            doorImage.setRotation(180f);
                            break;
                    }
                }
                TextView door_label = holder.itemView.findViewById(R.id.door_label);
                if (door_label != null) {
                    ViewGroup.LayoutParams labelParams = door_label.getLayoutParams();
                    labelParams.width = widthPx;
                    labelParams.height = heightPx;
                    door_label.setLayoutParams(labelParams);
                }

                break;



        }
    }

    @Override
    public int getItemCount() {
        return elements.size();
    }
    static class ElementHolder extends RecyclerView.ViewHolder {
        public ElementHolder(@NonNull View itemView) {
            super(itemView);
        }
    }
    private void loadQyAdminList(Spinner spinnerAdminList, String token, String seatPlace) {
        QyAdminListRequest request = new QyAdminListRequest(1, 10, seatPlace);
        Log.d("loadQyAdminList", "请求体: " + new Gson().toJson(request));
        Log.d("loadQyAdminList", "请求头 Authorization: " + token);

        ApiService apiService = ApiClient.getClient().create(ApiService.class);
        apiService.getQyAdminList(token, request).enqueue(new Callback<ApiResponse<List<UserItem>>>() {
            @Override
            public void onResponse(Call<ApiResponse<List<UserItem>>> call, Response<ApiResponse<List<UserItem>>> response) {
                Log.d("loadQyAdminList", "response.isSuccessful = " + response.isSuccessful());
                if (response.body() != null) {
                    Log.d("loadQyAdminList", "response.body().isSuccess = " + response.body().isSuccess());
                    Log.d("loadQyAdminList", "response.body().message = " + response.body().getMessage());
                    Log.d("loadQyAdminList", "response.body().data = " + new Gson().toJson(response.body().getData()));
                } else {
                    Log.d("loadQyAdminList", "response.body is null");
                }
                if (response.isSuccessful() && response.body() != null && response.body().isSuccess()) {
                    List<UserItem> adminList = response.body().getData();

                    // 提取名字列表
                    List<String> nameList = new ArrayList<>();
                    List<Long> idList = new ArrayList<>();
                    for (UserItem user : adminList) {
                        nameList.add(user.getUserName());
                        idList.add(user.getId());
                    }

                    // 设置 Spinner
                    ArrayAdapter<String> adapter = new ArrayAdapter<>(context, android.R.layout.simple_spinner_item, nameList);
                    adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
                    spinnerAdminList.setAdapter(adapter);

                    // 将 idList 存入 tag，便于后续取出
                    spinnerAdminList.setTag(idList);
                } else {
                    Toast.makeText(context, "获取区域管理员失败", Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onFailure(Call<ApiResponse<List<UserItem>>> call, Throwable t) {
                Toast.makeText(context, "网络请求失败：" + t.getMessage(), Toast.LENGTH_SHORT).show();
            }
        });
    }
    private void showReservationDialog(Context context, String backendRoomId, String backendSeatNum, String roomId, int seatId) {
        CustomSizeDialog dialog = new CustomSizeDialog(context, R.layout.dialog_reservation, 0.41f, 0.65f);

        dialog.setOnShowListener(d -> {
            Spinner spinnerAdminList = dialog.findViewById(R.id.spinnerAdminList);
            AppCompatSpinner spinnerStartHour = dialog.findViewById(R.id.spinner_start_hour);
            AppCompatSpinner spinnerStartMinute = dialog.findViewById(R.id.spinner_start_minute);
            AppCompatSpinner spinnerEndHour = dialog.findViewById(R.id.spinner_end_hour);
            AppCompatSpinner spinnerEndMinute = dialog.findViewById(R.id.spinner_end_minute);
            forceSetSpinnerHeight(spinnerStartHour, 8, 50);
            forceSetSpinnerHeight(spinnerStartMinute, 8, 50);
            forceSetSpinnerHeight(spinnerEndHour, 8, 50);
            forceSetSpinnerHeight(spinnerEndMinute, 8, 50);

            DatePicker datePicker = dialog.findViewById(R.id.date_picker);
            LinearLayout layout_hide = dialog.findViewById(R.id.layout_hide);

            SharedPreferences sp = context.getSharedPreferences("Session", Context.MODE_PRIVATE);
            String token = sp.getString("token", null);
            Long userId = sp.getLong("userId", 0);
            String qyAdmin = sp.getString("qy", null);

            ApiService apiService = ApiClient.getClient().create(ApiService.class);
            final boolean[] approvalEnabled = {true};

            // 填充 Spinner 数据（小时 0–23，分钟 0–59）
            List<String> hours = new ArrayList<>();
            List<String> minutes = new ArrayList<>();
            for (int i = 0; i < 24; i++) hours.add(String.format("%02d", i));
            for (int i = 0; i < 60; i++) minutes.add(String.format("%02d", i));

            ArrayAdapter<String> hourAdapter = new ArrayAdapter<>(context, R.layout.spinner_item_centered, hours);
            ArrayAdapter<String> minuteAdapter = new ArrayAdapter<>(context, R.layout.spinner_item_centered, minutes);
            hourAdapter.setDropDownViewResource(R.layout.spinner_item_centered);
            minuteAdapter.setDropDownViewResource(R.layout.spinner_item_centered);

            spinnerStartHour.setAdapter(hourAdapter);
            spinnerStartMinute.setAdapter(minuteAdapter);
            spinnerEndHour.setAdapter(hourAdapter);
            spinnerEndMinute.setAdapter(minuteAdapter);

            // 设置默认时间：开始为2分钟后，结束为1小时后
            Calendar now = Calendar.getInstance();
            now.add(Calendar.MINUTE, 2);
            spinnerStartHour.setSelection(now.get(Calendar.HOUR_OF_DAY));
            spinnerStartMinute.setSelection(now.get(Calendar.MINUTE));
            now.add(Calendar.HOUR_OF_DAY, 1);
            spinnerEndHour.setSelection(now.get(Calendar.HOUR_OF_DAY));
            spinnerEndMinute.setSelection(now.get(Calendar.MINUTE));

            // 查询是否开启审批
            apiService.getOpenStatus().enqueue(new Callback<ApiResponse<OpenStatusResponse>>() {
                @Override
                public void onResponse(Call<ApiResponse<OpenStatusResponse>> call, Response<ApiResponse<OpenStatusResponse>> response) {
                    if (response.isSuccessful() && response.body() != null && response.body().isSuccess()) {
                        approvalEnabled[0] = "true".equalsIgnoreCase(response.body().getData().open);
                        if (!approvalEnabled[0]) {
//                            layout_hide.setVisibility(View.INVISIBLE);
                        } else {
                            layout_hide.setVisibility(View.VISIBLE);
                            loadQyAdminList(spinnerAdminList, token, backendRoomId);
                        }
                    }
                }

                @Override
                public void onFailure(Call<ApiResponse<OpenStatusResponse>> call, Throwable t) {
                    Toast.makeText(context, "无法判断审批状态", Toast.LENGTH_SHORT).show();
                }
            });

            // 加载预约详情
            RecyclerView recyclerBookingDetail = dialog.findViewById(R.id.recycler_booking_detail);
            recyclerBookingDetail.setLayoutManager(new LinearLayoutManager(context));
            PageSeatListRequest request = new PageSeatListRequest(1, 1000);
            apiService.seatList(request).enqueue(new Callback<PageSeatListResponse>() {
                @Override
                public void onResponse(Call<PageSeatListResponse> call, Response<PageSeatListResponse> response) {
                    if (response.isSuccessful() && response.body() != null) {
                        for (SeatItem seat : response.body().getData().getData()) {
                            if (seat.getSeatPlace().equals(backendRoomId) && seat.getSeatNum().equals(backendSeatNum)) {
                                List<SsrSeatBooking> bookingList = seat.getSsrSeatBookingList();
                                Log.d("预约记录", new Gson().toJson(bookingList));
                                if (bookingList != null && !bookingList.isEmpty()) {
                                    BookingDetailAdapter adapter = new BookingDetailAdapter(bookingList);
                                    recyclerBookingDetail.setAdapter(adapter);
                                }
                                break;
                            }
                        }
                    }
                }

                @Override
                public void onFailure(Call<PageSeatListResponse> call, Throwable t) {
                    Toast.makeText(context, "加载预约详情失败", Toast.LENGTH_SHORT).show();
                }
            });

            // 提交预约
            dialog.findViewById(R.id.btn_confirm_booking).setOnClickListener(btn -> {
                int year = datePicker.getYear();
                int month = datePicker.getMonth();
                int day = datePicker.getDayOfMonth();

                int startHour = spinnerStartHour.getSelectedItemPosition();
                int startMinute = spinnerStartMinute.getSelectedItemPosition();
                int endHour = spinnerEndHour.getSelectedItemPosition();
                int endMinute = spinnerEndMinute.getSelectedItemPosition();

                Calendar start = Calendar.getInstance();
                Calendar end = Calendar.getInstance();
                start.set(year, month, day, startHour, startMinute);
                end.set(year, month, day, endHour, endMinute);

                //预约时间限制
                if (end.getTimeInMillis() <= start.getTimeInMillis()) {
                    Toast.makeText(context, "结束时间必须大于开始时间", Toast.LENGTH_SHORT).show();
                    return;
                }
                long durationMillis = end.getTimeInMillis() - start.getTimeInMillis();
                long minDurationMillis = 30 * 60 * 1000; // 30分钟
                long maxDurationMillis = 4 * 60 * 60 * 1000; // 4小时
                if (durationMillis < minDurationMillis) {
                    Toast.makeText(context, "预约时长不能少于30分钟", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (durationMillis > maxDurationMillis) {
                    Toast.makeText(context, "预约时长不能超过4小时", Toast.LENGTH_SHORT).show();
                    return;
                }

                String dateStr = String.format("%04d-%02d-%02d", year, month + 1, day);
                String startStr = dateStr + String.format(" %02d:%02d:00", startHour, startMinute);
                String endStr = dateStr + String.format(" %02d:%02d:00", endHour, endMinute);

                if (token == null || userId == null) {
                    Toast.makeText(context, "请先登录", Toast.LENGTH_SHORT).show();
                    return;
                }

                BookingSaveRequest saveRequest = new BookingSaveRequest(backendRoomId, backendSeatNum, startStr, endStr, userId);
                saveRequest.setQyAdmin(qyAdmin);

                if (approvalEnabled[0]) {
                    int selectedIndex = spinnerAdminList.getSelectedItemPosition();
                    List<Long> adminIds = (List<Long>) spinnerAdminList.getTag();
                    if (adminIds != null && selectedIndex >= 0 && selectedIndex < adminIds.size()) {
                        saveRequest.setApprover(adminIds.get(selectedIndex));
                    } else {
                        Toast.makeText(context, "请选择一个管理员", Toast.LENGTH_SHORT).show();
                        return;
                    }
                    saveRequest.setInitiator(userId);
                }

                apiService.getOpenStatus().enqueue(new Callback<ApiResponse<OpenStatusResponse>>() {
                    @Override
                    public void onResponse(Call<ApiResponse<OpenStatusResponse>> call, Response<ApiResponse<OpenStatusResponse>> response) {
                        if (response.isSuccessful() && response.body() != null && response.body().isSuccess()) {
                            String enableFlag = "true".equalsIgnoreCase(response.body().getData().open) ? "true" : "false";
                            apiService.saveBooking(token, enableFlag, saveRequest).enqueue(new Callback<ApiResponse<Object>>() {
                                @Override
                                public void onResponse(Call<ApiResponse<Object>> call, Response<ApiResponse<Object>> response) {
                                    if (response.isSuccessful() && response.body() != null && response.body().isSuccess()) {
                                        Toast.makeText(context, "预约成功", Toast.LENGTH_SHORT).show();
                                        for (LayoutElement e : elements) {
                                            if ("seat".equals(e.type) && e.roomId != null && e.roomId.equals(roomId) && e.id == seatId) {
                                                e.seatStatus = "3";
                                                break;
                                            }
                                        }
                                        notifyDataSetChanged();
                                        if (context instanceof ClassActivity) ((ClassActivity) context).refreshStats();
                                        dialog.dismiss();
                                    } else {
                                        Toast.makeText(context, "预约失败：" +
                                                (response.body() != null ? response.body().getMessage() : "未知错误"), Toast.LENGTH_LONG).show();
                                    }
                                }

                                @Override
                                public void onFailure(Call<ApiResponse<Object>> call, Throwable t) {
                                    Toast.makeText(context, "网络请求失败：" + t.getMessage(), Toast.LENGTH_SHORT).show();
                                }
                            });
                        }
                    }

                    @Override
                    public void onFailure(Call<ApiResponse<OpenStatusResponse>> call, Throwable t) {
                        Toast.makeText(context, "无法判断审批状态", Toast.LENGTH_SHORT).show();
                    }
                });
            });
        });

        dialog.show();
    }
    public static void forceSetSpinnerHeight(AppCompatSpinner spinner, int itemCount, int itemHeightDp) {
        try {
            float scale = spinner.getContext().getResources().getDisplayMetrics().density;
            int popupHeight = (int) (itemHeightDp * itemCount * scale + 0.5f);

            Field popupField = AppCompatSpinner.class.getDeclaredField("mPopup");
            popupField.setAccessible(true);
            Object popup = popupField.get(spinner);

            if (popup != null) {
                Method setHeightMethod = popup.getClass().getMethod("setHeight", int.class);
                setHeightMethod.invoke(popup, popupHeight);
            } else {
                Log.w("SpinnerFix", "⚠️ popup 为 null");
            }
        } catch (Exception e) {
            Log.e("SpinnerFix", "❌ 无法强制设置 Spinner 高度", e);
        }
    }



}
